import './style.scss'
import React from 'react'
import type { FC } from 'react'
import { Button, Divider, Form, Input, Flex, message } from 'antd'
// 在ts环境中，要是类型模块，建议用单独方式加type引入
import type { FormProps } from 'antd'
import { userLoginAction } from '@/reducers/user'
import { useAppDispatch, useAppSelector } from '@/store/hooks'
// Navigate 导航组件
import { useNavigate, Navigate } from 'react-router-dom'

const Login: FC = () => {
  const dispatch = useAppDispatch()
  const navigate = useNavigate()
  const token = useAppSelector((state) => state.user.userinfo.token)
  // Form组件提供一个hook，用来得到ref对象
  const [form] = Form.useForm()
  // 提示
  const [messageApi, contextHolder] = message.useMessage()

  // 表单提交验证通过执行的事件
  const onFinish: FormProps<IUserType.ILoginForm>['onFinish'] = async (
    values
  ) => {
    let code = await dispatch(userLoginAction(values))
    // 登录成功
    if (code == 0) {
      messageApi.success('登录成功', 1, () => {
        navigate('/info/dashoard', { replace: true })
      })
    } else {
      messageApi.error('账号或密码不正确', 3)
    }
  }

  // 表单提交验证失败执行的事件
  const onFinishFailed: FormProps<IUserType.ILoginForm>['onFinishFailed'] = (
    errorInfo
  ) => {
    messageApi.open({
      type: 'error',
      content: '表单项验证不通过，请认真填写',
      duration: 3
    })
  }

  // token存在表示已经登录过
  if (token) {
    return <Navigate to="/info/dashoard" />
  }

  return (
    <>
      {contextHolder}
      <div className="login-box">
        <h3>用户登录</h3>
        <Divider />
        <Form
          form={form}
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 16 }}
          initialValues={{ username: 'aa', password: 'bb' }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
        >
          <Form.Item<IUserType.ILoginForm>
            label="账号"
            name="username"
            rules={[
              { required: true, whitespace: true, message: '账号不能为空' },
              {
                validator: async (rule, value: string) => {
                  // 异步判断
                  if (value && value.includes('z')) {
                    return Promise.reject('有关键字存在')
                  }
                  return Promise.resolve()
                }
              }
            ]}
          >
            <Input />
          </Form.Item>

          <Form.Item<IUserType.ILoginForm>
            label="密码"
            name="password"
            rules={[
              {
                required: true,
                whitespace: true,
                message: '密码不能为空'
              }
            ]}
          >
            <Input />
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 4, span: 16 }}>
            <Flex gap="small">
              <Button type="primary" htmlType="submit">
                进入系统
              </Button>
              <Button
                type="default"
                onClick={() => {
                  form.resetFields()
                }}
              >
                重置表单
              </Button>
            </Flex>
          </Form.Item>
        </Form>
      </div>
    </>
  )
}

export default Login
